package com.zzl.bonds.ticket.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzl.bonds.ticket.constant.StringConstant;
import com.zzl.bonds.ticket.constant.UserCategoryConstant;
import com.zzl.bonds.ticket.constant.status.CreditStatusEnum;
import com.zzl.bonds.ticket.constant.type.CreditTypeEnum;
import com.zzl.bonds.ticket.constant.type.OperateButtonEnum;
import com.zzl.bonds.ticket.dao.CoreEnterpriseCreditDao;
import com.zzl.bonds.ticket.dto.CoreEnterpriseCreditAddDto;
import com.zzl.bonds.ticket.dto.CoreEnterpriseCreditUpdateDto;
import com.zzl.bonds.ticket.dto.KeyValue;
import com.zzl.bonds.ticket.dto.TicketOpenAddDto;
import com.zzl.bonds.ticket.dto.credit.*;
import com.zzl.bonds.ticket.entity.CoreEnterpriseCreditEntity;
import com.zzl.bonds.ticket.entity.EnterpriseCreditDataEntity;
import com.zzl.bonds.ticket.entity.SubsidiaryQuotaEntity;
import com.zzl.bonds.ticket.entity.TicketOpenEntity;
import com.zzl.bonds.ticket.service.CoreEnterpriseCredidataService;
import com.zzl.bonds.ticket.service.CoreEnterpriseCreditService;
import com.zzl.bonds.ticket.service.SubsidiaryQuotaService;
import com.zzl.general.common.constant.Constant;
import com.zzl.general.common.exception.SysException;
import com.zzl.general.common.serurity.entity.User;
import com.zzl.general.common.utils.PageUtils;
import com.zzl.general.common.utils.QmBeanUtils;
import com.zzl.general.common.utils.Query;
import com.zzl.general.common.utils.UuidUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 核心企业授信表
 *
 * @author sunpp
 * @date 2022-02-16 11:14:07
 */
@Slf4j
@Service("coreEnterpriseCreditService")
public class CoreEnterpriseCreditServiceImpl extends ServiceImpl<CoreEnterpriseCreditDao, CoreEnterpriseCreditEntity> implements CoreEnterpriseCreditService {


    @Autowired
    private SubsidiaryQuotaService subsidiaryQuotaService;

    @Autowired
    private CoreEnterpriseCredidataService coreEnterpriseCredidataService;

    @Autowired
    private CoreEnterpriseCredidataService credidataService;

    /**
     * 根据 授信id 获取 核心企业授信 或者 分公司集团授信
     *
     * @param creditId 授信id
     */
    @Override
    public CreditQuota getCreditOrQuotaById(String creditId) {
        // 如果核心企业的授信未找到 则找分公司的额度
        CreditQuota creditQuota = new CreditQuota();
        QueryWrapper<CoreEnterpriseCreditEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CoreEnterpriseCreditEntity::getId, creditId)
                .eq(CoreEnterpriseCreditEntity::getCreditType, CreditTypeEnum.GROUP.getCode());
        List<CoreEnterpriseCreditEntity> list = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            //分公司的 额度
            SubsidiaryQuotaEntity quotaEntity = subsidiaryQuotaService.getById(creditId);
            BeanUtils.copyProperties(quotaEntity, creditQuota);
            creditQuota.setCreditAvailableAmount(quotaEntity.getAvailableAmount());
            creditQuota.setCreditFrozenAmount(quotaEntity.getFrozenAmount());
            creditQuota.setCreditSurplusAmount(quotaEntity.getSurplusAmount());
            creditQuota.setCreditLockAmount(quotaEntity.getFrozenAmount());
            creditQuota.setCreditType(quotaEntity.getCreditType());
            return creditQuota;
        } else {
            CoreEnterpriseCreditEntity creditEntity = list.get(0);
            if (CreditStatusEnum.NOT_AVAILABLE_LIST.contains(creditEntity.getCreditStatus())) {
                return null;
            }
            BeanUtils.copyProperties(creditEntity, creditQuota);
            return creditQuota;
        }
    }

    /**
     * 回滚 核心企业的授信 或者 是 集团额度的
     *
     * @param id     授信id
     * @param amount 金额
     * @param user   登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void rollBackCoreCredit(String id, Double amount, User user) throws SysException {
        log.info("回滚授信额度{}{}{}", id, amount, user);
        CoreEnterpriseCreditEntity coreEntity = getEntityById(id);
        if (ObjectUtils.isEmpty(coreEntity)) {
            // 处理分公司的 集团授信 回滚
            String coreCreditId = subsidiaryQuotaService.rollBackSubQuota(id, amount, user);
            // 处理 分公司的所属的集团授信 冻结 和 可用额度的 回滚
            coreEntity = this.getEntityById(coreCreditId);
            if (ObjectUtils.isEmpty(coreEntity)) {
                throw new SysException("更新 集团授信时，未找到数据");
            }
        }
        rollBackCoreCredit(coreEntity, amount, user);

    }

    /**
     * 回滚核心企业的授信额度
     *
     * @param coreEntity 核心企业授信id
     * @param amount     金额
     * @param user       登录用户
     */
    public void rollBackCoreCredit(CoreEnterpriseCreditEntity coreEntity, Double amount, User user) {
        coreEntity.setUpdateTime(new Date());
        coreEntity.setUpdaterId(user.getId());
        if (coreEntity.getCreditFrozenAmount() - amount > 0) {
            coreEntity.setCreditFrozenAmount(coreEntity.getCreditFrozenAmount() - amount);
        } else {
            coreEntity.setCreditFrozenAmount(0.0);
        }

        coreEntity.setCreditAvailableAmount(coreEntity.getCreditAvailableAmount() + amount);
        this.updateById(coreEntity);
    }

    /**
     * 处理 核心企业 或者厂子的 的冻结 金额
     * 适用 开立中 转让中 融资中 将金额冻结
     */
    @Override
    public void handCoreCredit(String id, Double amount, User user) throws SysException {
        CoreEnterpriseCreditEntity coreEntity = getEntityById(id);
        if (ObjectUtils.isEmpty(coreEntity)) {
            // 处理分公司的 集团授信
            String coreCreditId = subsidiaryQuotaService.handSubQuota(id, amount, user);
            // 处理 分公司的所属的集团授信 冻结 和 可用额度的 扣减
            CoreEnterpriseCreditEntity entityById = this.getEntityById(coreCreditId);
            if (ObjectUtils.isEmpty(entityById)) {
                throw new SysException("更新 集团授信时，未找到数据");
            }
            updateReduceCredit(entityById, amount, user);

        } else {
            updateCoreCredit(coreEntity, amount, user);
        }
    }

    /**
     * 处理 授信的扣减 包括核心企业的授信 或者是 厂子的  集团授信 厂子的独立授信
     *
     * @param id     授信id
     * @param amount 数量
     * @param user   登录用户
     */
    @Override
    public void handReduceCredit(String id, Double amount, User user) throws SysException {
        log.info("心企业授信额度真实扣减{}{}{}", id, "金额", amount);
        CoreEnterpriseCreditEntity coreEntity = getEntityById(id);
        if (ObjectUtils.isEmpty(coreEntity)) {
            // 用的是 分公司的 集团授信
            String coreCreditId = subsidiaryQuotaService.handReduceSubQuota(id, amount, user);
            // 处理 分公司的所属的集团授信 冻结 和 可用额度的 扣减
            CoreEnterpriseCreditEntity entityById = this.getEntityById(coreCreditId);
            if (ObjectUtils.isEmpty(entityById)) {
                throw new SysException("扣减 集团授信时，未找到数据");
            }
            updateReduceCredit(entityById, amount, user);
        } else {
            updateReduceCredit(coreEntity, amount, user);
        }
    }

    /**
     * 处理 核心企业的授信 扣减
     *
     * @param coreEntity 授信实体
     * @param amount     数量
     * @param user       登录用户
     */
    private void updateReduceCredit(CoreEnterpriseCreditEntity coreEntity, Double amount, User user) {
        coreEntity.setUpdateTime(new Date());
        coreEntity.setUpdaterId(user.getId());
        coreEntity.setCreditFrozenAmount(coreEntity.getCreditFrozenAmount() + amount);
        coreEntity.setCreditAvailableAmount(coreEntity.getCreditAvailableAmount() - amount);
        this.updateById(coreEntity);
    }

    /**
     * 处理 冻结额度 和 可用额度
     *
     * @param coreEntity 核心企业实体
     * @param amount     数量
     * @param user       登录用户
     */
    private void updateCoreCredit(CoreEnterpriseCreditEntity coreEntity, Double amount, User user) {
        coreEntity.setCreditFrozenAmount(coreEntity.getCreditFrozenAmount() + amount);
        coreEntity.setCreditAvailableAmount(coreEntity.getCreditAvailableAmount() - amount);
        coreEntity.setUpdaterId(user.getId());
        coreEntity.setUpdateTime(new Date());
        this.updateById(coreEntity);
    }

    /**
     * 根据开单企业 找授信
     *
     * @param openEnterpriseId 开单企业id
     * @return 授信
     */
    @Override
    public List<CreditSelectDto> getCreditByOpenEnterpriseId(String openEnterpriseId) {
        List<CreditSelectDto> list = new ArrayList<>();
        /*TODO*/

        // 分公司的 集团授信
        List<CreditSelectDto> subQuotas = subsidiaryQuotaService.getSubQuotaByEnterpriseId(openEnterpriseId);
        if (!CollectionUtils.isEmpty(subQuotas)) {
            list.addAll(subQuotas);
        }
        return list;
    }

    /**
     * 获取
     *
     * @param ids ids
     * @return CoreEnterpriseCreditEntity
     */
    @Override
    public List<CoreEnterpriseCreditEntity> getEntityByCoreCreditIds(List<String> ids) {
        QueryWrapper<CoreEnterpriseCreditEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().in(CoreEnterpriseCreditEntity::getId, ids)
                .eq(CoreEnterpriseCreditEntity::getLatestStatus, 1);
        return this.list(queryWrapper);

    }

    /**
     * 获取开立授信额度
     *
     * @param ticketOpenAddDto 开单信息
     * @param entity           开单实体
     * @return 授信数据
     */
    @Override
    public InstitutyTemp getOpenCredit(TicketOpenAddDto ticketOpenAddDto, TicketOpenEntity entity) throws SysException {
        String creditId = ticketOpenAddDto.getCoreEnterpriseCreditId();
        Double amount = ticketOpenAddDto.getTicketAmount();
        // 如果核心企业的授信未找到 则找分公司的额度
        QueryWrapper<CoreEnterpriseCreditEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CoreEnterpriseCreditEntity::getId, creditId)
                .eq(CoreEnterpriseCreditEntity::getCreditType, CreditTypeEnum.GROUP.getCode());
        List<CoreEnterpriseCreditEntity> list = this.list(queryWrapper);
        InstitutyTemp institution;
        if (CollectionUtils.isEmpty(list)) {
            //分公司的 额度
            SubsidiaryQuotaEntity quotaEntity = subsidiaryQuotaService.getById(creditId);
            if (ObjectUtils.isEmpty(quotaEntity)) {
                throw new SysException("当前核心企业的授信额度未找到");
            }
            if (quotaEntity.getAvailableAmount() < amount) {
                throw new SysException("当前核心企业可用额度不足");
            }
            institution = new InstitutyTemp(quotaEntity.getInstitutyId(), quotaEntity.getInstitutyName());
        } else {
            CoreEnterpriseCreditEntity creditEntity = list.get(0);
            // 验证 授信时间是否在 有效期内
            Date date = new Date();
            if (date.after(creditEntity.getExpiryDate()) || date.before(creditEntity.getEffectiveDate())) {
                throw new SysException("当前授信额度未生效");
            }
            if (creditEntity.getCreditAvailableAmount() < amount) {
                throw new SysException("当前核心企业可用额度不足");
            }
            institution = new InstitutyTemp(creditEntity.getInstitutyId(), creditEntity.getInstitutyName());
        }
        entity.setInstinctyId(institution.getInstitutyId());
        entity.setInstinctyName(institution.getInstitutyName());
        return institution;
    }

    /**
     * 分页查询
     *
     * @param params 查询参数
     * @return 分页数据
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, User user) throws SysException {
        /**
         * 核心企业看自己
         */
        if (UserCategoryConstant.USER_CATEGORY_ENTERPRISE.getKey().equals(user.getUserCategory())) {
            params.put("enterpriseId", user.getEnterpriseId());
        } else if (UserCategoryConstant.USER_CATEGORY_GROUP.getKey().equals(user.getUserCategory())) {
            //集团看所有
        } else {
            throw new SysException("当前用户无查看权限");
        }
        //排序字段：create_time
        String pageField = (String) params.get(Constant.PAGE);
        //排序方式 order:  desc asc
        String order = (String) params.get(Constant.ORDER);
        IPage<CoreEnterpriseCreditPage> page = new Query<CoreEnterpriseCreditPage>()
                .getPage(params, StringUtils.isBlank(pageField)
                        ? StringConstant.CREATE_TIME_FILED : pageField, Constant.ASC.equals(order));
        IPage<CoreEnterpriseCreditPage> resultPage = this.baseMapper.queryCoreEnterpriseCreditPage(page, params);
        List<CoreEnterpriseCreditPage> resultPageRecords = resultPage.getRecords();
        if (!CollectionUtils.isEmpty(resultPageRecords)) {
            List<String> strings = resultPageRecords.stream().map(CoreEnterpriseCreditPage::getId).distinct().collect(Collectors.toList());
            Map<String, List<EnterpriseCreditDataEntity>> map = coreEnterpriseCredidataService.getByCoreEnterpriseIds(strings);
            for (CoreEnterpriseCreditPage resultPageRecord : resultPageRecords) {
                List<KeyValue> buttons = new ArrayList<>();
                resultPageRecord.setCreditStatusStr(CreditStatusEnum.getStatusName(resultPageRecord.getCreditStatus()));
                resultPageRecord.setCreditTypeStr(CreditTypeEnum.getValue(resultPageRecord.getCreditType()));
                buttons.add(new KeyValue(OperateButtonEnum.DETAILS.getCode(), OperateButtonEnum.DETAILS.getValue()));
                if (!ObjectUtils.isEmpty(map)) {
                    List<EnterpriseCreditDataEntity> entities = map.get(resultPageRecord.getId());
                    resultPageRecord.setDatas(entities);
                }
                // 平台的额度列表增加 修改按钮
                Object platObj = params.get("plat");
                if (!ObjectUtils.isEmpty(platObj) && StringConstant.PLAT.equals(platObj.toString())) {
                    buttons.add(new KeyValue(OperateButtonEnum.MODIFY.getCode(), OperateButtonEnum.MODIFY.getValue()));
                }
                resultPageRecord.setOperateButton(buttons);
            }
        }
        return new PageUtils(resultPage);
    }


    @Override
    public StatisticCreditDataDto getOpenData(User user) {
        return this.baseMapper.getThreeData(user.getEnterpriseId());
    }


    /**
     * 获取 核心企业授信详情
     *
     * @param id 核心企业授信id
     * @return 详情数据v
     * @throws SysException 业务异常
     */
    @Override
    public CoreCreditDetail getCoreCreditDetail(String id) throws SysException {
        CoreCreditDetail detail = new CoreCreditDetail();
        CoreEnterpriseCreditEntity creditEntity = this.getById(id);
        if (ObjectUtils.isEmpty(creditEntity)) {
            throw new SysException("未查到当前授信");
        }
        BeanUtils.copyProperties(creditEntity, detail);
        // 额度管理的 list
        // 所有的 分公司的企业数据
        List<SubsidiaryQuotaEntity> subQuotaList = subsidiaryQuotaService.getSubQuotaList(creditEntity.getId());
        if (!CollectionUtils.isEmpty(subQuotaList)) {
            List<SubsidiaryQuotaDto> dtos = QmBeanUtils.copyListProperties(subQuotaList, SubsidiaryQuotaDto::new);
            detail.setSubsidiaryQuotaList(dtos);
        }

        return detail;
    }

    @Override
    public CoreEnterpriseCreditEntity getEntityById(String id) {
        QueryWrapper<CoreEnterpriseCreditEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CoreEnterpriseCreditEntity::getId, id)
                .eq(CoreEnterpriseCreditEntity::getLatestStatus, 1);
        List<CoreEnterpriseCreditEntity> list = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 获取 核心企业 授信的 可用金额
     *
     * @return 金额
     */
    @Override
    public Double getCoreAvailableAmount(String id) {
        CoreEnterpriseCreditEntity entity = this.getEntityById(id);
        if (ObjectUtils.isEmpty(entity)) {
            // 分公司的 集团额度
            SubsidiaryQuotaEntity quotaEntity = subsidiaryQuotaService.getById(id);
            return quotaEntity.getAvailableAmount();
        }
        return entity.getCreditAvailableAmount();
    }

    /**
     * 新增
     *
     * @param coreEnterpriseCreditAddDto 新增实体
     * @param user                       当前登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void saveCoreEnterpriseCredit(CoreEnterpriseCreditAddDto coreEnterpriseCreditAddDto, User user) throws SysException {
        CoreEnterpriseCreditEntity coreEnterpriseCreditEntity = new CoreEnterpriseCreditEntity();
        BeanUtils.copyProperties(coreEnterpriseCreditAddDto, coreEnterpriseCreditEntity);
        coreEnterpriseCreditEntity.setCreatorId(user.getId());
        if (!this.save(coreEnterpriseCreditEntity)) {
            throw new SysException("A00001", "保存失败！");
        }
    }


    /**
     * 修改
     *
     * @param coreEnterpriseCreditUpdateDto 修改实体
     * @param user                          当前登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void updateCoreEnterpriseCreditById(CoreEnterpriseCreditUpdateDto coreEnterpriseCreditUpdateDto, User user) throws SysException {
        CoreEnterpriseCreditEntity coreEnterpriseCreditEntity = new CoreEnterpriseCreditEntity();
        BeanUtils.copyProperties(coreEnterpriseCreditUpdateDto, coreEnterpriseCreditEntity);
        coreEnterpriseCreditEntity.setUpdaterId(user.getId());
        if (!this.updateById(coreEnterpriseCreditEntity)) {
            throw new SysException("A00002", "修改失败！");
        }
    }

    /**
     * 根据 金融机构id 统计核心企业的授信总额度
     *
     * @return
     */
    @Override
    public Map<String, Double> getAllAmountByInstityId() {
        QueryWrapper<CoreEnterpriseCreditEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CoreEnterpriseCreditEntity::getEnterpriseId, 1)
                .eq(CoreEnterpriseCreditEntity::getLatestStatus, 1);
        List<CoreEnterpriseCreditEntity> list = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            return list.stream().collect(Collectors.groupingBy(CoreEnterpriseCreditEntity::getInstitutyId, Collectors.summingDouble(CoreEnterpriseCreditEntity::getCreditAllAmount)));
        }
        return null;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUpdateCoreCredit(AddOrUpdateCreditDto addOrUpdateCreditDto, User user) throws SysException {
        log.info("新增修改授信额度入参：{}，用户信息：{}", JSON.toJSONString(addOrUpdateCreditDto), user);
        List<EnterpriseCreditDataEntity> datas = addOrUpdateCreditDto.getDatas();
        if (CollectionUtils.isEmpty(datas)) {
            throw new SysException("授信资料不能为空");
        }
        // 3.11 产品确认 不用处理 同一家企业 在一家金融机构 在同一期限内的 限制
        if (ObjectUtils.isEmpty(addOrUpdateCreditDto.getId())) {
            // 新增 数据
            CoreEnterpriseCreditEntity entity = new CoreEnterpriseCreditEntity();
            BeanUtils.copyProperties(addOrUpdateCreditDto, entity);
            entity.setId(UuidUtils.UUID());
            entity.setCreateTime(new Date());
            entity.setCreditNo(UuidUtils.UUID());
            entity.setCreatorId(user.getId());
            entity.setCreditAvailableAmount(addOrUpdateCreditDto.getCreditAllAmount());
            entity.setCreditSurplusAmount(addOrUpdateCreditDto.getCreditAllAmount());
            entity.setCreditUsedAmount(0.0);
            entity.setCreditFrozenAmount(0.0);
            entity.setDeletedStatus(0);
            entity.setCreditStatus(CreditStatusEnum.SUCCESS.getCode());
            entity.setCreditStatus(1);
            entity.setInstitutyId(addOrUpdateCreditDto.getFinanceInstitutyId());
            entity.setInstitutyName(addOrUpdateCreditDto.getFinanceInstitutyName());
            setCreditStatus(entity);
            this.save(entity);
            datas.forEach(x -> x.setCreditId(entity.getId()));
            credidataService.addUpdateCreditDatas(datas, entity.getId(), user);
        } else {
            // 修改数据
            CoreEnterpriseCreditEntity creditEntity = this.getById(addOrUpdateCreditDto.getId());
            if (ObjectUtils.isEmpty(creditEntity)) {
                throw new SysException("未查到修改的数据");
            }
            log.info("修改数据核心企业的授信信息{}", creditEntity.toString());
            // 重复性 校验
            if (!creditEntity.getCreditNo().equals(addOrUpdateCreditDto.getCreditNo())) {
                List<CoreEnterpriseCreditEntity> list = this.list();
                Optional<CoreEnterpriseCreditEntity> first = list.stream().filter(x -> x.getCreditNo().equals(addOrUpdateCreditDto.getCreditNo())).findFirst();
                if (first.isPresent()) {
                    throw new SysException("该修改的 编号已经存在");
                }
            }
            // 处理冻结状态的逻辑
            if (addOrUpdateCreditDto.getLockStatus().equals(1)) {
                Double creditLockAmount = addOrUpdateCreditDto.getCreditLockAmount();
                Double oldLockAmount = creditEntity.getPlatFrozenAmount();
                if (ObjectUtils.isEmpty(creditLockAmount)) {
                    throw new SysException("冻结额度不能为空");
                }
                // 重新设置 可用额度
                if (creditLockAmount > creditEntity.getCreditAllAmount()) {
                    throw new SysException("冻结金额不能大于额度总金额");
                }
                BeanUtils.copyProperties(addOrUpdateCreditDto, creditEntity);
                double changeAmount = creditLockAmount - oldLockAmount;
                if (changeAmount >= creditEntity.getCreditAvailableAmount()) {
                    creditEntity.setCreditAvailableAmount(0.0);
                } else {
                    // 可用额度 和 冻结额度的 是处于相反数的 状态
                    creditEntity.setCreditAvailableAmount(creditEntity.getCreditAvailableAmount() - changeAmount);
                }

            } else {
                if (!ObjectUtils.isEmpty(addOrUpdateCreditDto.getCreditLockAmount())) {
                    // 当点击了不冻结 并且有冻结金额  解冻部分金额
                    if (addOrUpdateCreditDto.getCreditLockAmount() > creditEntity.getPlatFrozenAmount()) {
                        throw new SysException("不冻结金额 大于 冻结金额");
                    }
                    BeanUtils.copyProperties(addOrUpdateCreditDto, creditEntity);
                    creditEntity.setPlatFrozenAmount(creditEntity.getPlatFrozenAmount() - addOrUpdateCreditDto.getCreditLockAmount());
                    creditEntity.setCreditAvailableAmount(creditEntity.getCreditAvailableAmount() + addOrUpdateCreditDto.getCreditLockAmount());
                }
            }
            creditEntity.setUpdaterId(user.getId());
            creditEntity.setUpdateTime(new Date());
            creditEntity.setInstitutyId(addOrUpdateCreditDto.getFinanceInstitutyId());
            creditEntity.setInstitutyName(addOrUpdateCreditDto.getFinanceInstitutyName());
            // 处理授信状态
            setCreditStatus(creditEntity);
            this.updateById(creditEntity);
            datas.forEach(x -> x.setCreditId(creditEntity.getId()));
            // 新增 授信的资料
            credidataService.addUpdateCreditDatas(datas, creditEntity.getId(), user);
        }
    }

    /**
     * 更新授信状态
     */
    @Override
    public void handCreditStatus() {
        List<CoreEnterpriseCreditEntity> list = this.list();
        Date date = new Date();
        for (CoreEnterpriseCreditEntity entity : list) {
            setCreditStatus(entity);
            entity.setUpdateTime(date);
        }
        this.updateBatchById(list);
    }

    /**
     * 设置 授信状态
     */
    private void setCreditStatus(CoreEnterpriseCreditEntity entity) {
        Date nowDate = new Date();
        if (nowDate.before(entity.getEffectiveDate())) {
            entity.setCreditStatus(CreditStatusEnum.NOT_EFFECTIVE.getCode());
        } else if (nowDate.after(entity.getExpiryDate())) {
            entity.setCreditStatus(CreditStatusEnum.FAIL.getCode());
        } else {
            entity.setCreditStatus(CreditStatusEnum.SUCCESS.getCode());
        }
    }
}